from django.shortcuts import render
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from oauth.serializers import UserInfoSerializer
from .models import User
from rest_framework.generics import GenericAPIView,CreateAPIView,RetrieveAPIView,UpdateAPIView
from rest_framework import mixins
from . import serializers
from rest_framework.permissions import IsAuthenticated
from .serializers import RegisterUserSerializer, AddressSerializer
from rest_framework.viewsets import GenericViewSet

class CheckUsernameView(APIView):
    def get(self,request,username):
        count = User.objects.filter(username=username).count()
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)

class CheckMobileView(APIView):
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()
        data = {
            "count":count
        }
        return Response(data,status=status.HTTP_200_OK)

class RegisterUserView(CreateAPIView):
    #设置序列化器
    serializer_class = RegisterUserSerializer
    # def post(self,request):
    #     #1获取参数
    #     dict_data = request.data
    #     #2校验参数,生成序列化器校验
    #     #获取序列化器参数,并传递参数到序列化器
    #     serializer = self.get_serializer(data=dict_data)
    #     #运行序列化器
    #     serializer.is_valid(raise_excertion=True)
    #     #3数据入库
    #     serializer.save()
    #     #4返回响应
    #     return Response(serializer.data,status=status.HTTP_201_CREATED)

class UserInfoView(RetrieveAPIView):
    serializer_class = serializers.UserInfoSerializer
    # 下面这句是限制了只有认证的用户才可以进去的限制
    permission_classes = [IsAuthenticated] #认证的用户
    def get_object(self):
        return self.request.user
        # def get(self,request):
        #     #一, 单纯使用二级视图实现
        #     # #1,获取用户对象(或者request.user)
        #     # user =  self.get_object()
        #     #
        #     # #2,创建序列化对象
        #     # serializer = self.get_serializer(instance=user)
        #     #
        #     # #3,返回数据
        #     # return Response(serializer.data)
        #
        #     #二,二级视图配合mixin
        #     return self.retrieve(request)

class EmailSendView(UpdateAPIView):
    serializer_class = serializers.EmailSendSerializer
    permission_classes = [IsAuthenticated]
    def get_object(self):
        # 以下这步是DRF封装的东西
        return self.request.user
        # def put(self,request):
        #     #一, 单纯使用二级视图实现
        # #1,获取数据
        # dict_data = request.data
        # user = self.get_object()
        #
        # #2,获取序列化器
        # serializer = self.get_serializer(instance=user,data=dict_data)
        #
        # #3,校验,入库
        # serializer.is_valid(raise_exception=True)
        # serializer.save()
        #
        # #4,返回
        # return Response(serializer.data)
        #     #二,二级视图配合mixin
        # return self.update(request)
        #前段代码看不懂？？？？然后获取数据为什么没有传过来都可以获取的么？底层如何实现？？？？？

class EmailActiveView(APIView):
    def get(self,request):
        #1.獲取參數token
        token = request.query_params.get("token")
        # 爲空校驗
        if not token:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # ３，解密ｔｏｋｅｎ（调用了user model 里面的方法）
        user = User.decode_token(token)
        if not user:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        # ４．数据入库
        user.email_active = True
        user.save()
        # 返回响应
        return Response(status=status.HTTP_200_OK)

class AddressView(mixins.DestroyModelMixin,mixins.CreateModelMixin,mixins.UpdateModelMixin,GenericViewSet):
    serializer_class = serializers.AddressSerializer
    permission_classes = [IsAuthenticated]
    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)
    def list(self,request):
    # 获取用户信息
        queryset = self.get_queryset()
    # 获取序列化器
        serializer = self.get_serializer(instance=queryset,many=True)#instance是一个固定传递参数方法，当传递的参数不是一个的时候就要用ｍａｎｙ
    # 返回

        return Response({
            "addresses":serializer.data,#为什么是。data??
            "limit":20,
            "default_address_id": request.user.default_address_id
        })

    def create(self, request, *args, **kwargs):
        # 1,获取用户地址数量
        count = request.user.addresses.filter(is_deleted=False).count()

        # 2,判断地址的数量
        if count >= 20:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 3,调用父类方法即可
        return super(AddressView, self).create(request, *args, **kwargs)
        # 为什么要用super?

    @action(methods=['put'], detail=True)  # 格式: addresses/pk/status
    def status(self, request, pk):
        request.user.default_address_id = pk
        request.user.save()
        return Response(status=status.HTTP_200_OK)

    @action(methods=["put"], detail=True)
    def title(self, request, pk):
        # 1,获取参数
        dict_data = request.data
        address = self.get_object()

        # 2,创建序列化器
        serializer = serializers.AddressTitleSerializer(instance=address, data=dict_data)

        # 3,校验数据,入库
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # 4,返回
        return Response(serializer.data)

    # 4,重写destory方法,为了逻辑删除
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_deleted = True
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

class TestView(APIView):
    def get(self,request,name,age):
        print(self.kwargs)
        return Response("%s,%s" %(name,age))